package cn.com.idmy.auth.context;

import cn.com.idmy.base.util.Assert;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

import static cn.com.idmy.auth.AuthConfig.ACCOUNT_TYPE_KEY;


public class SpringServletContextImpl implements Context {
    @NotNull
    static HttpServletRequest httpServletRequest() {
        var tmp = Assert.notNull((ServletRequestAttributes) RequestContextHolder.getRequestAttributes(), "非 web 上下文无法获取 HttpServletRequest");
        return tmp.getRequest();
    }

    @NotNull
    static HttpServletResponse httpServletResponse() {
        var tmp = Assert.notNull((ServletRequestAttributes) RequestContextHolder.getRequestAttributes(), "非 web 上下文无法获取 HttpServletRequest");
        return Objects.requireNonNull(tmp.getResponse());
    }

    @Override
    public long accountType() {
        var req = httpServletRequest();
        var at = req.getAttribute(ACCOUNT_TYPE_KEY);
        Assert.notNull(at, "无需鉴权的接口，无法获取账号类型");
        return (long) at;
    }

    @Override
    public @NotNull Request request() {
        return new RequestForServlet(httpServletRequest());
    }

    @Override
    public @NotNull Response response() {
        return new ResponseForServlet(httpServletResponse());
    }

    @Override
    public @NotNull Storage storage() {
        return new StorageForServlet(httpServletRequest());
    }
}
